package com.pphh.demo;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixThreadPoolProperties;

/**
 * Please add description here.
 *
 * @author huangyinhuang
 * @date 11/22/2018
 */
public class TestCommand extends HystrixCommand<String> {

    public static final String DONE = "done";
    public static final String FAIL = "fail";

    private FlowControl hystricFlowControl;

    protected TestCommand(FlowControl task, HystrixCommandProperties.ExecutionIsolationStrategy isolationStrategy) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"))
                .andCommandPropertiesDefaults(initHystrixCommandProperties(isolationStrategy))
                .andThreadPoolPropertiesDefaults(initHystrixThreadProperties()));
        this.hystricFlowControl = task;
    }


    public static HystrixCommandProperties.Setter initHystrixCommandProperties(HystrixCommandProperties.ExecutionIsolationStrategy isolationStrategy) {
        return HystrixCommandProperties.Setter()
                .withExecutionIsolationStrategy(isolationStrategy)
                .withExecutionTimeoutEnabled(true)
                .withExecutionTimeoutInMilliseconds(200)
                .withExecutionIsolationSemaphoreMaxConcurrentRequests(5)
                .withFallbackIsolationSemaphoreMaxConcurrentRequests(5)
                .withCircuitBreakerRequestVolumeThreshold(100)
                .withCircuitBreakerSleepWindowInMilliseconds(2000);
    }

    public static HystrixThreadPoolProperties.Setter initHystrixThreadProperties() {
        return HystrixThreadPoolProperties.Setter()
                .withCoreSize(5)
                .withMaximumSize(5)
                .withMaxQueueSize(-1);
    }

    @Override
    protected String run() throws Exception {
        hystricFlowControl.test();
        return DONE;
    }

    @Override
    protected String getFallback() {
        return FAIL;
    }
}
